import React from 'react';
import { Layout, Menu } from 'antd';
import { NavLink, withRouter } from 'react-router-dom';
import menus, { IFMenu } from '../routers/config';
import * as Icon from '@ant-design/icons';
import '../style/customize/app.less';

const { Sider } = Layout;
const { SubMenu } = Menu;
type SiderCustomProps = {
  collapsed?: boolean;
};

class SiderCustom extends React.Component<SiderCustomProps> {
  // 动态生成Icon
  generateIcon = (name: string) =>
    React.createElement(Icon && (Icon as any)[name], {
      className: 'ct-text-base',
    });

  // 父节点菜单项
  renderSubMenu = (item: IFMenu) => {
    return (
      <SubMenu
        key={item.key}
        title={item.title}
        icon={item.icon ? this.generateIcon(item.icon) : ''}
      >
        {item.subs!.map((val) =>
          val.subs ? this.renderSubMenu(val) : this.renderMenuItem(val)
        )}
      </SubMenu>
    );
  };

  // 子节点菜单项
  renderMenuItem = (item: IFMenu) => {
    return (
      <Menu.Item
        key={item.key}
        title={item.title}
        icon={item.icon ? this.generateIcon(item.icon) : ''}
      >
        <NavLink className="ct-menu-item" to={item.key + (item.query || '')}>
          <span className="nav-text">{item.title}</span>
        </NavLink>
      </Menu.Item>
    );
  };

  render() {
    return (
      <Sider trigger={null} collapsible collapsed={this.props.collapsed}>
        <div className="h-8 m-4 bg-gray-400 rounded-sm" />
        <Menu theme="dark" mode="inline">
          {menus.menus.map((val: IFMenu) => {
            return val.subs
              ? this.renderSubMenu(val)
              : this.renderMenuItem(val);
          })}
        </Menu>
      </Sider>
    );
  }
}

export default withRouter(SiderCustom);
